package com.draven.controller;

import com.draven.common.PageQuery;
import com.draven.common.Result;
import com.draven.entity.OperationLog;
import com.draven.mapper.SysUserMapper;
import com.draven.service.OperationLogService;
import com.draven.service.SysUserService;
import com.draven.vo.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.Min;

/**
 * 操作日志控制器
 */
@RestController
@RequestMapping("/operationLog")
public class OperationLogController {

    @Autowired
    private OperationLogService operationLogService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 分页查询操作日志
     */
    @GetMapping("/page")
    public Result<?> page(
            HttpServletRequest request,
            @RequestParam(required = false) String module,
            @RequestParam(required = false) String operationType,
            @RequestParam(required = false) Integer status,
            @Valid PageQuery pageQuery) {
        // 获取当前用户ID（管理员可查看所有日志，普通用户只能查看自己的）
        Long userId = (Long) request.getAttribute("userId");
        UserInfoVO userInfo = sysUserService.getUserInfo(userId);
        if (userInfo == null) {
            return Result.error(403, "无权限操作");
        }
        boolean isAdmin=userInfo.getNickname().equals("管理员");
        // 构建查询条件
        OperationLog condition = new OperationLog();
        if (!isAdmin) {
            condition.setUserId(userId);
        }
        condition.setModule(module);
        condition.setOperationType(operationType);
        condition.setStatus(status);
        
        return operationLogService.pageList(pageQuery, condition);
    }
    
    /**
     * 清理指定天数之前的日志（仅管理员可操作）
     */
    @DeleteMapping("/clean")
    public Result<Integer> clean(
            HttpServletRequest request,
            @Min(value = 1, message = "天数必须大于0") @RequestParam Integer days) {
        // 检查是否为管理员
        Boolean isAdmin = (Boolean) request.getAttribute("isAdmin");
        if (!isAdmin) {
            return Result.error(403, "无权限操作");
        }
        
        int count = operationLogService.cleanLogs(days);
        return Result.success(count);
    }
} 